package com.daiyu.sharding.sharding.hint;

import org.apache.shardingsphere.infra.hint.HintManager;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class HintAspect {

    @Pointcut("@annotation(com.daiyu.sharding.sharding.hint.Hint)")
    public void hintPointcut() {

    }

    @Around("hintPointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        try (HintManager hintManager = HintManager.getInstance()) {
            // HintManager 只是个标识
            hintManager.addDatabaseShardingValue("ds", 2);
            hintManager.addTableShardingValue("t_product", 5);
            return point.proceed();
        }
    }

    private Method getCurrentMethod(ProceedingJoinPoint point) {
        try {
            Signature sig = point.getSignature();
            MethodSignature msig = (MethodSignature) sig;
            Object target = point.getTarget();
            return target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }
}
